package com.ali.sqlSession;

import com.ali.io.Resources;
import com.ali.pogo.Configuration;
import com.ali.pogo.MappedStatement;
import com.ali.pogo.SqlCommandType;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.print.DocFlavor;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XmlMapperBuild {
    private Configuration configuration;

    public XmlMapperBuild(Configuration configuration) {
        this.configuration = configuration;
    }

    public Configuration builder(InputStream in) throws Exception {
        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//*");
        String namespace = rootElement.attributeValue("namespace");
        Properties properties = new Properties();

        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String name = element.getName();
            String sql = element.getTextTrim();
            String key = namespace + "." + id;
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(key);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sql);

            if (name == "select") {
                mappedStatement.setSqlType(SqlCommandType.SELECT);
            } else if (name == "update") {
                mappedStatement.setSqlType(SqlCommandType.UPDATE);
            } else if (name == "delete") {
                mappedStatement.setSqlType(SqlCommandType.DELETE);
            } else if (name == "insert") {
                mappedStatement.setSqlType(SqlCommandType.INSERT);
            }
            configuration.getMappedStatementMap().put(key, mappedStatement);
            System.out.println(mappedStatement);

        }
        /**
         * 将接口加入到configuration的MapperRegister 注册到自己的map集合中
         */
        bindMapperForNameSpace(namespace);
        return configuration;
    }

    /**
     * 将namespace 对应的接口类加入到configuration.mapperRegister的集合中
     *
     * @param namespace
     */
    private void bindMapperForNameSpace(String namespace) {
        if (namespace != null) {
            Class<?> aClass = null;
            try {
                aClass = Resources.classForName(namespace);
            } catch (Exception e) {
            }
            boolean b = this.configuration.hasMapper(aClass);
            if (aClass != null && !this.configuration.hasMapper(aClass)) {
                this.configuration.addMapper(aClass);
            }

        }
    }

}
